<template>
  <div>
    <div class="tree">
      <el-input
        placeholder="输入关键字,进行检索"
        v-model="filterText">
      </el-input>
      <el-tree
        ref="tree2"
        :data="treeJson"
        :props="defaultProps"
        :accordion="flag"
        empty-text="节点树为空"
        class="filter-tree men"
        highlight-current
        :filter-node-method="filterNode"
        @node-click="handleNodeClick">
      </el-tree>
    </div>
    <div class="context">
      <div id="node_info" class="panel panel-default">
        <div class="panel-heading"><b>配置节点</b></div>
        <div class="panel-body">
          <div class="container-fluid">
            <div class="row" style="padding : 10px 0px">
              <div class="col-md-9 input-group">
                <el-input placeholder="暂无数据" v-model="menuItem.id" :disabled=flag>
                  <template slot="prepend">节点编号</template>
                </el-input>
              </div>
            </div>
            <div class="row" style="padding : 10px 0px">
              <div class="col-md-9 input-group">
                <el-input placeholder="暂无数据" v-model="menuItem.path" :disabled=flag>
                  <template slot="prepend">节点路径</template>
                </el-input>
              </div>
            </div>
            <div class="row" style="padding : 10px 0px">
              <div class="col-md-9 input-group">
                <el-input placeholder="暂无数据" v-model="menuItem.englishName" :disabled=flag>
                  <template slot="prepend">英文名称</template>
                </el-input>
              </div>
            </div>
            <div class="row" style="padding : 10px 0px">
              <div class="col-md-9 input-group">
                <el-input placeholder="暂无数据" v-model="menuItem.chineseName" :disabled=flag>
                  <template slot="prepend">中文名称</template>
                </el-input>
              </div>
            </div>
            <div class="row" style="padding : 10px 0px">
              <div class="col-md-9 input-group">
                <span class="input-group-addon" style="background-color: #fbfdff;color: #97a8be;">节点管理</span>
                <el-input
                  type="textarea"
                  :disabled=flag
                  :autosize="{ minRows: 1}"
                  placeholder="该节点暂无管理员"
                  v-model="menuItem.manager">
                </el-input>
              </div>
            </div>
            <div class="row" style="padding : 10px 0px">
              <div class="col-md-9 input-group">
                <span class="input-group-addon" style="background-color: #fbfdff;color: #97a8be;">绑定配置集</span>
                <el-select v-model="menuItem.cfgmap" placeholder="请选择" disabled>
                  <el-option
                    v-for="item in selectMaps"
                    :key="item.id"
                    :label="item.description"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span class="wrapper">
        <el-button type="success" @click="showAddNodeDialog">新增子节点</el-button>
        <el-popover
          ref="popover5"
          placement="top"
          transition
          width="160"
          v-model="visible2">
          <p>确定删除该节点 <span style="font-weight: bold;color: red">{{menuItem.chineseName}}</span> 吗？</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="visible2 = false">取消</el-button>
            <el-button type="primary" size="mini" @click="delNode">确定</el-button>
          </div>
        </el-popover>
        <el-button type="danger" v-popover:popover5 style="margin-left: 7px;">删除选中节点</el-button>
        <el-button type="info" @click="showLogDialog">查看配置日志</el-button>
        <el-button type="primary" @click="showTransferDialog">权限配置<i
          class="el-icon-setting el-icon--right"></i></el-button>
      </span>
    </div>
    <el-dialog title="新增配置节点" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="addNodeFormRules" ref="addForm">
        <el-form-item label="中文名称" :label-width="formLabelWidth">
          <el-input v-model="form.cname" placeholder="用来做菜单展示"></el-input>
        </el-form-item>
        <el-form-item label="英文名称" :label-width="formLabelWidth" prop="ename">
          <el-input v-model="form.ename" placeholder="当前节点path = 父节点path + 该节点英文名称"></el-input>
        </el-form-item>
        <el-form-item label="管理员" :label-width="formLabelWidth">
          <el-select v-model="form.authman" multiple placeholder="请选择管理员" style="width: 100%" filterable>
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="绑定配置集" :label-width="formLabelWidth">
          <el-select v-model="form.cfgmap" placeholder="请选择配置集">
            <el-option :label="m.description" :value="m.id" v-for="m in selectMaps" :key="m.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveNode">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="节点权限配置" :visible.sync="dialogTransferVisible">
      <div style="margin-left: 60px;">
        <el-transfer
          filterable
          :filter-method="filterMethod"
          filter-placeholder="输入花名或工号进行检索"
          :titles="['用户列表', '已选用户']"
          v-model="selectedUsers"
          :data="users">
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTransferVisible = false">取 消</el-button>
        <el-button type="primary" @click="editAuth">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="操作日志查询" :visible.sync="dialogLogVisible" size="full">
      <div style="margin: 10px auto">
        <div class="block">
          <el-tag>查询周期 &nbsp;:&nbsp;</el-tag>
          <el-date-picker
            size="small"
            v-model="value3"
            type="datetimerange"
            placeholder="选择时间范围">
          </el-date-picker>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <el-tag>操作人 &nbsp;:&nbsp;</el-tag>
          <el-select v-model="optUser" placeholder="请选择" size="small">
            <el-option
              v-for="item in users"
              :key="item.key"
              :label="item.label"
              :value="item.label">
            </el-option>
          </el-select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <el-button icon="search" size="small">搜索</el-button>
        </div>
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          label="日期"
          width="200">
          <template scope="scope">
            <el-icon name="time"></el-icon>
            <span style="margin-left: 10px">{{ scope.row.date }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="姓名"
          width="150">
          <template scope="scope">
            <el-tag type="gray">{{ scope.row.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template scope="scope">
            <el-button
              size="small"
            >编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="margin: 10px auto;float: right">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage4"
          :page-sizes="[5, 10, 15, 20 ]"
          :page-size="50"
          layout="total, sizes, prev, pager, next, jumper"
          :total="100">
        </el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
  .tree {
    float: left;
    width: 300px;
    margin-top: 10px;
  }

  .context {
    position: absolute;
    left: 320px;
    right: 20px;
    margin-top: 10px;
  }

  .info-row {
    background: #c9e5f5;
  }

  .positive-row {
    background: #e2f0e4;
  }
</style>

<script>
  import fetch from "../../store/uacc_api";
  import {mapState, mapMutations} from 'vuex';
  export default {
    data() {
      return {
        options:[],
        value3: '',
        optUser: '',
        currentPage4: 4,
        selectedUsers: [],
        users: [],
        selectMaps: [],
        filterMethod(query, item) {
          return item.label.indexOf(query) > -1;
        },
        flag: true,
        dialogFormVisible: false,
        dialogTransferVisible: false,
        visible2: false,
        dialogLogVisible: false,
        form: {
          cname: '',
          ename: '',
          authman: [],
          cfgmap: ''
        },
        formLabelWidth: '120px',
        menuItem: {
          id: '',
          path: '',
          chineseName: '',
          englisheName: '',
          cfgmap: '',
          manager:[]
        },
        addNodeFormRules: {
          ename: [
            { required: true, message: '请输入英文名称', trigger: 'blur' },
            { min: 3, message: '长度至少3个字符', trigger: 'blur' }
          ]
        },
        defaultProps: {
          children: 'childNodes',
          label: 'description'
        },
        tableData: [{
          date: '2016-05-02 16:24:32',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        }, {
          date: '2016-05-04 16:24:32',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1517 弄'
        }, {
          date: '2016-05-01 16:24:32',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1519 弄'
        }, {
          date: '2016-05-03 16:24:32',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1516 弄'
        }],
        filterText:''
      };
    },
    computed: {
      ...mapState(['cfgMaps','currentUser']),
      treeJson(){
        if (this.$store.state.treeJson) {
          let arr = [];
          arr.push(this.$store.state.treeJson);
          return arr;
        }
        return null;
      }
    },
    watch: {
      filterText(val) {
        this.$refs.tree2.filter(val);
      }
    },
    methods: {
      ...mapMutations(['editTree']),
      //点击节点在右侧展示
      handleNodeClick(data) {
        if (data) {
          var maps = [{description: '请选择', id: ''}];
          this.selectMaps = maps.concat(this.cfgMaps);
          this.menuItem.id = data.id;
          this.menuItem.path = data.nodePath;
          this.menuItem.englishName = data.name;
          this.menuItem.chineseName = data.description;
          this.menuItem.cfgmap = data.configStruct.id;
          this.getUsersOfNode();
        }
      },
      getAllUsers(){
        let me = this;
        fetch.getAllUser().then(function (res) {
          if (res.success) {
            let allUser = res.data;
            me.form.authman.push(me.currentUser.empId);
            allUser.forEach((user) => {
              me.options.push({
                label: user.nickName,
                value: user.empId
              })
            });
          }
        });
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.description.indexOf(value) !== -1;
      },
      saveNode(){
        this.$refs.addForm.validate((valid) => {
            if (valid) {
              let me = this;
              this.dialogFormVisible = false;
              let emps = '';
              if (this.form.authman) {
                this.form.authman.forEach(function (emp) {
                  emps = emps + emp + ',';
                });
                emps = emps.substring(0, emps.length - 1);
              }
              let node = {
                configStruct: {id: this.form.cfgmap},
                description: this.form.cname,
                name: this.form.ename,
                empIds:emps,
                nodePath: this.menuItem.path + '/' + this.form.ename,
                version: 0
              };
              this.$refs['addForm'].resetFields();
              let param = {'data': JSON.stringify(node)};
              fetch.addTreeNode(param).then(function (res) {
                if (res.success) {
                  me.$message({
                    showClose: true,
                    type: 'success',
                    message: '添加节点成功'
                  });
                  //刷新全局菜单treeJson
                  me.queryNode();
                } else {
                  me.$message({
                    showClose: true,
                    type: 'error',
                    message: res.errorMessage
                  });
                }
              })
            }
          }
        )
      },
      showAddNodeDialog()
      {
        if (!this.menuItem.path) {
          this.$message({
            showClose: true,
            type: 'info',
            message: '请先选择父节点！'
          });
          return;
        }
        if (this.menuItem.path == '/root') {
          this.$message({
            showClose: true,
            type: 'info',
            message: '请前往应用注册页面，添加配置空间'
          });
          return;
        }
        var maps = [{description: '请选择', id: ''}];
        this.selectMaps = maps.concat(this.cfgMaps);
        this.form.cname = '',
          this.form.ename = '',
          this.form.authman = [],
          this.form.cfgmap = '',
          //获取全部人员，并将自己设置为默认管理员
          this.getAllUsers();
          this.dialogFormVisible = true;
      },
      showLogDialog()
      {
        if (!this.menuItem.path) {
          this.$message({
            showClose: true,
            type: 'info',
            message: '请先选择节点！'
          });
          return;
        }
        let me = this;
        this.optUser = '';
        this.users = [];
        //查询所有用户列表
        fetch.getAllUser().then(function (res) {
          if (res.success) {
            let allUser = res.data;
            allUser.forEach((user) => {
              me.users.push({
                label: user.nickName ? user.nickName + ' [' + user.empId + ']' : user.lastName + ' [' + user.empId + ']',
                key: user.empId
              })
            });
          }
        });
        this.dialogLogVisible = true;
      }
      ,
      showTransferDialog()
      {
        if (!this.menuItem.path) {
          this.$message({
            showClose: true,
            type: 'info',
            message: '请先选择节点！'
          });
          return;
        }
        let me = this;
        this.users = [];
        this.selectedUsers = [];
        //查询所有用户列表
        fetch.getAllUser().then(function (res) {
          if (res.success) {
            let allUser = res.data;
            allUser.forEach((user) => {
              me.users.push({
                label: user.nickName ? user.nickName + ' [' + user.empId + ']' : user.lastName + ' [' + user.empId + ']',
                key: user.empId
              })
            });
          }
        });
        this.getUsersOfNode();
        this.dialogTransferVisible = true;
      }
      ,
      editAuth()
      {
        let me = this;
        this.dialogTransferVisible = false;
        let tmpUser = '';
        this.selectedUsers.forEach(function (user) {
          tmpUser = tmpUser + (user + ',');
        });
        tmpUser = tmpUser.substring(0, tmpUser.length - 1);
        let param = {nodePath: this.menuItem.path, empIds: tmpUser};
        fetch.updateNodeUsers(param).then(function (res) {
          if (res.success) {
            me.$message({
              showClose: true,
              type: 'success',
              message: '操作成功'
            });
            //刷新管理员
            me.getUsersOfNode();
          } else {
            me.$message({
              showClose: true,
              type: 'error',
              message: res.errorMessage
            });
          }
        })
      }
      ,
      delNode()
      {
        this.visible2 = false;
        if (!this.menuItem.path) {
          this.$message({
            showClose: true,
            type: 'info',
            message: '请先选择节点！'
          });
          return;
        }
        let me = this;
        let param = {nodePath: this.menuItem.path};
        fetch.deleteTreeNode(param).then(function (res) {
          if (res.success) {
            me.$message({
              showClose: true,
              type: 'success',
              message: '删除节点成功'
            });
            me.menuItem.id = '',
              me.menuItem.path = '',
              me.menuItem.chineseName = '',
              me.menuItem.englisheName = '',
              me.menuItem.options = []
            //刷新全局菜单treeJson
            me.queryNode();
          } else {
            me.$message({
              showClose: true,
              message: '删除节点失败:' + res.errorMessage,
              type: 'error'
            });
          }
        })
      }
      ,
      getCookie(c_name)
      {
        if (document.cookie.length > 0) {
          let c_start = document.cookie.indexOf(c_name + "=")
          if (c_start != -1) {
            c_start = c_start + c_name.length + 1
            let c_end = document.cookie.indexOf(";", c_start)
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end))
          }
        }
        return ""
      }
      ,
      queryNode(param)
      {
        let me = this;
        fetch.queryNodes(param).then(function (resp) {
          if (resp.success) {
            let root = resp.data;
            me.editTree(root);
            let cookie = me.getCookie('SPACEID');
            if (cookie) {
              let menu = root.childNodes.cookie;
              if (menu) {
                me.editMenu(JSON.parse('[' + JSON.stringify(menu) + ']'));
              }
            }
          } else {
            console.error(resp);
            me.$message({
              showClose: true,
              message: resp.errorMessage,
              type: 'error'
            })
          }
        })
      }
      ,
      getUsersOfNode()
      {
        let me = this;
        fetch.getUsersOfNode({nodePath: this.menuItem.path}).then(function (resp) {
          if (resp.success) {
            let managers = '';
            resp.data.forEach((user) => {
              managers = managers + user.nickName +' ';
              me.selectedUsers.push(
                user.empId
              )
            });
            me.menuItem.manager = managers;
          }
        })
      }
      ,
      handleSizeChange(val)
      {
        console.log(`每页 ${val} 条`);
      }
      ,
      handleCurrentChange(val)
      {
        console.log(`当前页: ${val}`);
      }
    }
  }
</script>
